package com.xzz.hashmap;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: hhz
 * @create: 2022-01-26 19:06
 * 2013. 检测正方形
 **/
public class DetectSquares {
    //{x, {y : 点 (x,y) 数量}}
    Map<Integer, Map<Integer, Integer>> row2Col ;
    public DetectSquares() {
        row2Col = new HashMap<>();
    }

    public void add(int[] point) {
        int x = point[0];
        int y = point[1];
        Map<Integer, Integer> orDefault = row2Col.getOrDefault(x, new HashMap<>());
        orDefault.put(y,orDefault.getOrDefault(y,0)+1);
        row2Col.put(x,orDefault);
    }

    public int count(int[] point) {
        int x = point[0], y = point[1];
        int res = 0;
        Map<Integer, Integer> orDefault = row2Col.getOrDefault(x, new HashMap<>());
        for (Integer ny : orDefault.keySet()) {
            if(ny==y){
                continue;
            }
            int c1 = orDefault.get(ny);
            int len = y-ny;
            int[] nums = new int[]{x + len, x - len};
            for (int nx : nums) {
                Map<Integer, Integer> temp = row2Col.getOrDefault(nx, new HashMap<>());
                int c2 = temp.getOrDefault(y, 0);
                int c3 = temp.getOrDefault(ny, 0);
                res += c1 * c2 * c3;
            }
        }
        return res;
    }
}
